//
//  JWBoxDrawable.m
//  KotH
//
//  Created by James Weatherley on 16/08/2008.
//  Copyright 2008 James Weatherley. All rights reserved.
//

#import "../koth.h"

//#import <GLUT/GLUT.h>
#import "../wolfiphone.h"
#import "../jwglut/jwglut.h"


@implementation JWBoxManager


-(id)initWithEntity:(NSObject*)entity
{
	self = [super init];
	
	assert(entity == nil);
	boxList = [[NSMutableArray alloc] init];
	
	return self;
}

-(void)dealloc
{
	[super dealloc];
	[boxList release];
}

-(NSObject*)entity
{
	return boxList;
}

-(void)addEntity:(NSObject*)entity
{
	assert([entity isKindOfClass:[JWBox class]]);
	[boxList addObject:entity];
}

-(void)removeEntity:(NSObject*)entity
{
	assert([entity isKindOfClass:[JWBox class]]);
	JWBox* box = (JWBox*)entity;
	JWSquare* square = [box square];
	
	[square removeBox:box];
	
	NSArray* boxStack = [square boxes];
	NSInteger index = [box heightAboveSquare];
	for(NSInteger i = index; i < [boxStack count]; ++i) {
		[[boxStack objectAtIndex:i] lower];
	}
	
	[boxList removeObject:box];
}

-(void)removeAllEntities
{
	[boxList removeAllObjects];
}

-(NSArray*)boxList
{
	return boxList;
}

-(void)draw
{
	GLfloat* colour = 0;
	float size = 0.75f;
	
	JWBox* deadBox = nil;
	
	//pfglBegin(GL_QUADS);
	for(JWBox* box in boxList) {
		BOOL shouldDraw = [[[box square] boxes] containsObject:box];
		JWSquare* square = [box square];
		
		if(!shouldDraw && fabs([box heightAboveSquare] - [box heightAboveSquare]) <= JW_DEPS) {
			[[box square] updateTopBox];
			assert(!deadBox);
			deadBox = box;
		}
		
		if(shouldDraw) {
			if([box selected]) {
				colour = selectedColour;
			} else {
				colour = bark;
			}
			
			//qglMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, colour);
			pfglColor4f(colour[0], colour[1], colour[2], 1.0f);
			qglPushMatrix();
			{
				qglTranslatef(0.5f, 0.0f, 0.5f);
				qglTranslatef([square x], [square height] + [box heightAboveSquare] + size / 2.0f + 0.25, [square z]);
				glutSolidCube(size);
			}
			qglPopMatrix();
		}
	}
	//pfglEnd();
	
	if(deadBox) {
		[boxList removeObject:deadBox];
	}
}

-(void)postDraw
{
}

@end
